package com.lex;

import com.parse.ast.ASTNode;
import com.parse.ast.ASTNodeType;

import java.util.List;

public class TokenStream {
    private List<Token> tokens;
    public int currentTokenIndex;

    public TokenStream(List<Token> tokens) {
        this.tokens = tokens;
        this.currentTokenIndex = 0;
    }

    /**
     * 获取当前游标的token
     * 可能为注释
     * 不改变游标
     * @return
     */
    public Token getCurrentToken(){
        return tokens.get(currentTokenIndex);
    }


    /**
     * 获取当前节点下的非注释token
     * 注释token会加到当前节点
     * 不改变游标
     * @param thisAstNode
     * @return
     */
    public Token getCurrentToken(ASTNode thisAstNode){
        Token token = tokens.get(currentTokenIndex);
        if (token.getType().equals(TokenType.EOF)) {
            return new Token(TokenType.EOF, "",tokens.get(tokens.size()-1).getEnd(),tokens.get(tokens.size()-1).getEnd());
        }else if (token.getType().equals(TokenType.COMMENTS)){
            thisAstNode.addChild(new ASTNode(ASTNodeType.COMMENTS,token,thisAstNode));
            forwardToken();
            return getCurrentToken(thisAstNode);
        }else {
            return token;
        }
    }

    /**
     * 移动游标
     */
    public void forwardToken(){
        this.currentTokenIndex++;
    }

    /**
     * 查看下一个非注释token
     * 游标不会改变
     * @return
     */
    public Token catNextTokenNoComments(){
        int localIndex = currentTokenIndex;
        localIndex++;
        while (true){
            if (localIndex >= tokens.size()) {
                return new Token(TokenType.EOF, "",tokens.get(tokens.size()-1).getEnd(),tokens.get(tokens.size()-1).getEnd());
            } else if (tokens.get(localIndex).getType().equals(TokenType.COMMENTS)) {
                localIndex++;
            }else {
                return tokens.get(localIndex);
            }
        }
    }

    /**
     * 拿到下一个token
     * 可能为注释
     * 游标改变
     * @return
     */
    public Token getNextToken() {
        if (currentTokenIndex >= tokens.size()) {
            return new Token(TokenType.EOF, "",tokens.get(tokens.size()-1).getEnd(),tokens.get(tokens.size()-1).getEnd());
        }
        Token token = tokens.get(currentTokenIndex);
        currentTokenIndex++;
        return token;
    }
}


